//
//  AboutUsViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/5/26.
//

#import "AboutUsViewController.h"
#import "WebViewController.h"
#import <StoreKit/StoreKit.h>
#import "UpdateAlertView.h"


@interface AboutUsViewController ()
@property(nonatomic,strong)UpdateAlertView *updateView;
@property(nonatomic,strong)UILabel *numLabel;
@end

@implementation AboutUsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
}

-(void)createUI{
    [self.customNavigationBar setTitle:@"关于我们"];
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 10;
    bgView.layer.masksToBounds = YES;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+20);
        if(isIPAD){
            make.height.mas_equalTo(242);
        }else{
            make.height.mas_equalTo(kWFit(242));
        }
    }];
    __weak typeof(self)self_weak_ = self;
    NSArray *arr = @[@"检查更新",@"用户协议",@"隐私政策",@"备案编号"];
    for(NSInteger i = 0;i < arr.count;i++){
        UIView *bView = [[UIView alloc]initWithFrame:CGRectMake(0,i*kWFit(63), kScreenWidth-32,kWFit(53))];
        if(isIPAD){
            bView.frame = CGRectMake(0,i*63, self.currentAvailableWidth-32,53);
        }
        bView.tag = 100+i;
        [bgView addSubview:bView];
        if(i < 3){
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
                [self_weak_ jumpWithIndex:i];
            }];
            [bView addGestureRecognizer:tap];
        }
        UILabel *titleLabel = [[UILabel alloc]init];
        titleLabel.font = JPUIFontPingFangSCMedium(15);
        titleLabel.textColor = KFontBlackColor;
        titleLabel.text = arr[i];
        titleLabel.userInteractionEnabled = YES;
        [bView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(@16);
            make.height.mas_equalTo(@21);
            make.centerY.mas_equalTo(bView);
        }];
        if(i < 3){
            UIImageView *arrowImageView = [[UIImageView alloc]init];
            arrowImageView.image = [UIImage imageNamed:@"mine_right_arrow"];
            arrowImageView.userInteractionEnabled = YES;
            arrowImageView.tag = 200+i;
            [bView addSubview:arrowImageView];
            [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(@-12);
                make.width.height.mas_equalTo(@16);
                make.centerY.mas_equalTo(bView);
            }];
        }else if (i == 3){
            UILabel *numLabel = [[UILabel alloc]init];
            numLabel.font = JPUIFontPingFangSCRegular(14);
            numLabel.textColor = KFontGrayColor;
            numLabel.textAlignment = NSTextAlignmentRight;
            numLabel.text = @"津ICP备2024020413号-2A";
            [bView addSubview:numLabel];
            [numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(@-16);
                make.height.mas_equalTo(@21);
                make.centerY.mas_equalTo(bView);
            }];
            self.numLabel = numLabel;
        }
    }
    
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           // 获取当前可用宽度并更新布局
           self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
           self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
           self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            for(NSInteger i = 0;i < 4;i++){
                UIView *bView = [self.view viewWithTag:100+i];
                bView.frame = CGRectMake(0,i*63, self.currentAvailableWidth-32,53);
                if(i < 3){
                    UIImageView *arrowImageView = [bView viewWithTag:200+i];
                    [arrowImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.right.mas_equalTo(@-12);
                        make.centerY.mas_equalTo(bView);
                    }];
                }else if (i == 3){
                    [self.numLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.right.mas_equalTo(@-16);
                        make.centerY.mas_equalTo(bView);
                    }];
                }
            }
            if(self.updateView){
                self.updateView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
            }
        });
    }
}

-(void)jumpWithIndex:(NSInteger)index{
    if(index == 1||index == 2){
        WebViewController *vc = [[WebViewController alloc]init];
        if (index == 1) {
            vc.webUrlString = @"https://www.riyudao.com/guanwang/app/use.html";
            vc.titleStr = @"用户协议";
        }else if(index == 2) {
            vc.webUrlString = @"https://www.riyudao.com/guanwang/app/hide.html";
            vc.titleStr = @"隐私政策";
        }
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index == 0){
        //版本更新
        [self getAppVersion];
    }
}

#pragma mark - 获取app store版本号
-(void)getAppVersion{
    __weak typeof(self)self_weak_ = self;
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/lookup?id=%@",JPAPPID]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSError *jsonError;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
            if (!jsonError) {
                NSArray *results = json[@"results"];
                if (results.count > 0) {
                    NSDictionary *appInfo = results.firstObject;
                    NSString *storeVersion = appInfo[@"version"];
                    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
                    BOOL isVersionEqual = [storeVersion isEqualToString:currentVersion];
                    if (isVersionEqual) {
                        NSLog(@"当前版本与 App Store 版本一致");
                        dispatch_async(dispatch_get_main_queue(), ^{
                        [JPProgressHUD showMsg:@"当前已是最新版本"];
                        });
                    } else {
                        NSLog(@"当前版本与 App Store 版本不一致");
                        dispatch_async(dispatch_get_main_queue(), ^{
                            // 在主线程执行的代码
                            [self_weak_ showUpdateAlertViewWithVersion:storeVersion];
                        });
                    }
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://apps.apple.com/app/id%@",JPAPPID]];
                        if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
                            [[UIApplication sharedApplication] openURL:appStoreURL options:@{} completionHandler:nil];
                        }
                    });
                }
            } else {
                NSLog(@"解析 JSON 错误: %@", jsonError.localizedDescription);
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://apps.apple.com/app/id%@",JPAPPID]];
                    if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
                        [[UIApplication sharedApplication] openURL:appStoreURL options:@{} completionHandler:nil];
                    }
                });
            }
        } else {
            NSLog(@"请求 App Store 信息失败: %@", error.localizedDescription);
            dispatch_async(dispatch_get_main_queue(), ^{
                NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://apps.apple.com/app/id%@",JPAPPID]];
                if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
                    [[UIApplication sharedApplication] openURL:appStoreURL options:@{} completionHandler:nil];
                }
            });
        }
    }];
    [dataTask resume];
}

-(void)showUpdateAlertViewWithVersion:(NSString*)version{
    if(!self.updateView){
        self.updateView = [[UpdateAlertView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth, self.currentAvailableHeight) andVersion:version];
    }
    UIWindow *keyWindow = KEY_WINDOW;
    if(keyWindow){
        [keyWindow addSubview:self.updateView];
    }
    __weak typeof(self)self_weak_ = self;
    [self.updateView setUpdateBlock:^{
        [self_weak_.updateView removeFromSuperview];
        NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://apps.apple.com/app/id%@",JPAPPID]];
        if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
            [[UIApplication sharedApplication] openURL:appStoreURL options:@{} completionHandler:nil];
        }
    }];
}

@end
